package com.example.lt.authority;

import com.example.lt.exception.AuthorityException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @Author 小涛Tao
 * @Date: 2024/08/17/18:46
 * version 1.0 注释：
 **/
@Aspect
@Component
public class AuthorityAop {

    @Autowired
    private HttpServletRequest request;

    /**
     * 自定义权限校验
     * @param joinPoint 连接点
     * @param authority 自定义注解
     * @return
     * @throws Throwable
     */
    @Around("@annotation(authority)")
    public Object authority(ProceedingJoinPoint joinPoint, Authority authority) throws Throwable {
        Boolean result;
        Method method;
        Object verifyObject;
        if (AuthorityUtils.getGlobalVerify()) {
            // 全局校验类
            Class verifyClass = AuthorityUtils.getVerifyClass();
            verifyObject = verifyClass.newInstance();
            method = verifyClass.getMethod("authorityVerify", HttpServletRequest.class, String[].class);
            result = (Boolean) method.invoke(verifyObject, request, authority.value());
            if (!result) throw new AuthorityException("权限不足");
        }

        Object o = joinPoint.proceed();
        return o;
    }

}
